import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
// 导入全局样式表
import '../assets/css/global.css'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'


Vue.use(VueRouter)

/* 这是一个捕获异常的方法，防止路由守卫重复进入两次，报错（虽然页面还可以运行） */
/* const originalReplace = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalReplace.call(this, location).catch(err => err)
} */


const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/', redirect: '/login' },
    {
      path: '/home',
      component: Home,
      /*最开始重定向到Welcome.vue页面 */
      redirect: '/welcome',

      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/categories', component: Cate }
      ],
    }

  ]
})

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
  // to 表示要访问的路径
  // from表示从哪个路径跳转过来
  // next 是一个函数，表示放行
  // next（）表示放行，next('/login')表示强制跳转到 /login 页面
  if (to.path === '/login') {
    return next()
  }
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    return next('/login')
  } else {
    next()
  }
})

// 暴露路由守卫
export default router
